package com.situ.mall.admin.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * ClassName: ImageUtil
 * Package: com.situ.mall.util
 * Description:
 *
 * @Author Darling_达
 * @Create 2023-03-16 16:56
 * @Version 1.0
 */
public class ImageUtil {

    private static int randomColor() {
        return (int) (Math.random() * 255 + 1);
    }

    public static BufferedImage image(String code) {

        int width = 250, height = 100;
        // rgb不透明色
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();

        // 设置背景
        g.setColor(new Color(randomColor(), randomColor(), randomColor()));
        g.fillRect(0, 0, width, height);

        // 画干扰线
        g.setColor(new Color(randomColor(), randomColor(), randomColor()));
        g.drawLine(0, 0, 250, 100);
        g.drawLine(0, 100, 250, 0);
        g.drawLine(51, 10, 260, 84);

        // 设置颜色，字体，写出内容
        g.setColor(new Color(randomColor(), randomColor(), randomColor()));
        g.setFont(new Font("Times New Roman", Font.PLAIN, 80));

        g.drawString(code, 10, 80);

        // 生成图像
        g.dispose();
        return bi;
    }

    /**
     * @return 随机生成4位 验证码（数字、大写字母、小写字母）
     */
    public static String createCode() {
        StringBuilder codes = new StringBuilder();
        Random r = new Random();
        // 2.定义一个for循环，随机n次，随机生成字符
        for (int i = 0; i < 4; i++) {
            // 3.生成随机字符，可能是数字，大写字母，小写字母
            int num = r.nextInt(3);
            switch (num) {
                case 0:
                    // 数字:0-9
                    codes.append(r.nextInt(10));
                    break;
                case 1:
                    // 大写字母:A(65)-Z(65+25)
                    char ch1 = (char) (r.nextInt(26) + 65);
                    codes.append(ch1);
                    break;
                case 2:
                    // 小写字母:a(97)-z(97+25)
                    char ch2 = (char) (r.nextInt(26) + 97);
                    codes.append(ch2);
                    break;
            }
        }
        return codes.toString();
    }


}
